<?php

namespace app\api\controller;

use think\Db;
use think\Image;
use think\Controller;

//上传
class Upload extends Controller
{
    //上传图片
    public function uploadPic()
    {
        $width = input('post.width', 800);
        $height = input('post.height', 640);
        $token = input('post.token', '');
        $type = input('post.type', '');
        $posters = input('post.posters', '');
        if (!$token) {
            return error('缺少参数：token');
        }
        $file = request()->file('imgfile');
        if ($file) {
            // 移动到服务器的上传目录 并且使用md5规则 最大5M
            $info = $file->validate(['size' => 5242880, 'ext' => 'jpg,png'])->rule('md5')->move(ROOT_PATH.'public'.DS.'uploads');
            if ($info) {
                $image = Image::open(ROOT_PATH.'public'.DS.'uploads/'.$info->getSaveName());
                $image->thumb($width, $height, 'center' == $type ? Image::THUMB_CENTER : Image::THUMB_SCALING)->save(ROOT_PATH.'public/uploads/'.$info->getSaveName());
                if ($posters) {
                    Db::name('upload')->insert(['user_id' => $token, 'type' => '海报', 'img_url' => config('file_domain').'uploads/'.$info->getSaveName()]);
                }

                return success(config('file_domain').'uploads/'.$info->getSaveName());
            } else {
                return error('上传失败 '.$file->getError());
            }
        }

        return error('缺少参数：file');
    }
}
